package com.yanqu.road.server.gameplayer.module.activity.tomb.cmd;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.config.goods.OpenGoodsBagResult;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eItemId;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.log.LogTombUserRepair;
import com.yanqu.road.entity.player.UserBagItem;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.tomb.Tomb;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.tomb.TombMgr;
import com.yanqu.road.server.gameplayer.module.activity.tomb.TombModule;
import com.yanqu.road.server.gameplayer.module.player.BagModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.manger.config.GoodsBagMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.sync.message.SyncResponse;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;


import java.math.BigInteger;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

@Cmd(code = GameProtocol.S_TOMB_REPAIR, desc = "秦俑再世修复请求")
public class TombRepairCmd extends AbstractCommand {

    private Tomb.TombRepairReq req;

    private Tomb.TombRepairResp.Builder repairRespBuilder;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        this.req = Tomb.TombRepairReq.parseFrom(packet.getBytes());
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        this.repairRespBuilder = Tomb.TombRepairResp.newBuilder();
        //常规判断
        ActivityInfo activityInfo = TombMgr.getActivityInfo();
        this.repairRespBuilder.setFinish(0);
        if (activityInfo == null) {
            this.repairRespBuilder.setRet(GameErrorCode.E_ACTIVITY_NOT_OPEN);
            player.sendPacket(ClientProtocol.U_TOMB_REPAIR, this.repairRespBuilder);
            return;
        }

        //预扣除道具
        int costItem = TombMgr.getConfig().getConfig().getTOMB_REPAIR_ITEM_ID();
        long useItemNum = 0;
        //是否一键
        if (req.getOneKey() == 0) {
            String cost = costItem + "=" + 1;
            Property property = PropertyHelper.parseStringToProperty(cost);
            if (!player.getModule(CurrencyModule.class).currencyIsEnough(property)) { //物品不足
                ret = GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                repairRespBuilder.setRet(ret);
                player.sendPacket(ClientProtocol.U_TOMB_REPAIR, this.repairRespBuilder);
                return;
            }
            useItemNum = 1;
        } else {
            UserBagItem userBagItem = player.getModule(BagModule.class).getUserBagItem(costItem);
            if (userBagItem != null && userBagItem.getNum() > 0) {
                useItemNum = userBagItem.getNum();  // 背包拥有的所有黏土取出
            } else {         //物品不足
                ret = GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                repairRespBuilder.setRet(ret);
                player.sendPacket(ClientProtocol.U_TOMB_REPAIR, this.repairRespBuilder);
                return;
            }
        }
        //预扣除黏土
        Property costProperty = new Property(costItem, BigInteger.valueOf(useItemNum));
        if (!player.getModule(CurrencyModule.class).currencyIsEnough(costProperty)) { //物品不足
            ret = GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            repairRespBuilder.setRet(ret);
            player.sendPacket(ClientProtocol.U_TOMB_REPAIR, this.repairRespBuilder);
            return;
        }
        player.getModule(PreReduceModule.class).preReduce(costProperty);

        Tomb.TombRepairReq.Builder requestBuilder = req.toBuilder();
        requestBuilder.setUseItemNum(useItemNum);
        requestBuilder.setUnionUid(player.getUserInfo().getUnionUid());
        CompletableFuture<SyncResponse> future = GamePlayerMgr.sendToActivityCrossServerForUnionGroup(player.getUserId(), CrossProtocol.C_TOMB_REPAIR, activityInfo.getActivityId(), requestBuilder, this.repairRespBuilder);
        long finalUseItemNum = useItemNum;
        future.thenAccept(syncResponse -> {
            if (!this.repairRespBuilder.hasRet()) {
                this.repairRespBuilder.setRet(0);
            }
            player.getModule(PreReduceModule.class).restorePreReduce(costProperty);     //返回预扣除
            if (repairRespBuilder.getRet() != 0) {                 //不成功返回
                player.sendPacket(ClientProtocol.U_TOMB_REPAIR, this.repairRespBuilder);
                return;
            }
            if (repairRespBuilder.getRealUseNum() > 0) {
                //扣消耗
                costProperty.setGood(costItem, BigInteger.valueOf(repairRespBuilder.getRealUseNum()));
                if (!player.getModule(CurrencyModule.class).removeCurrency(costProperty, eLogMoneyType.Tomb, eLogMoneyType.TombRepairCost)){
                    ret = GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                    repairRespBuilder.setRet(ret);
                    player.sendPacket(ClientProtocol.U_TOMB_REPAIR, this.repairRespBuilder);
                    return;
                }
                //加奖励
                Property rewardProperty = new Property();
                for (int i = 0; i < repairRespBuilder.getRealUseNum(); i++) {
                    OpenGoodsBagResult openGoodsBagResult = GoodsBagMgr.getRandomGoods(costItem);
                    rewardProperty.addProperty(openGoodsBagResult.getReward());
                }
                player.getModule(CurrencyModule.class).addCurrency(rewardProperty, eLogMoneyType.Tomb, eLogMoneyType.TombRepairReward);
                this.repairRespBuilder.addReward(PropertyHelper.parsePropertyToString(rewardProperty));
            }
            int areaId = 0;
            long p = 0;
            Map<Integer, Long> progressMap = new ConcurrentHashMap<>();
            for (Tomb.TombRepairProgress progress : this.repairRespBuilder.getRepairDataList()) {
                int maxProgressByRepairZoneId = TombMgr.getMaxProgressByRepairZoneId(progress.getId());
                if (maxProgressByRepairZoneId > areaId) {
                    areaId = maxProgressByRepairZoneId;
                }
                if (maxProgressByRepairZoneId != 0) {
                    p = progress.getProgress() * 100 / maxProgressByRepairZoneId;

                    progressMap.put(progress.getId(), p);
                } else {
                    progressMap.put(progress.getId(), 0L);
                }
            }
            player.notifyListener(eGamePlayerEventType.TombUnionNianTuNum.getValue(), progressMap);   //同步商会进度
            player.sendPacket(ClientProtocol.U_TOMB_REPAIR, this.repairRespBuilder);


            LogTombUserRepair logTombUserRepair = new LogTombUserRepair();
            logTombUserRepair.setUserId(player.getUserId());
            logTombUserRepair.setActivityId(TombMgr.getActivityInfo().getActivityId());
            logTombUserRepair.setUnionUid(player.getUserInfo().getUnionUid());
            logTombUserRepair.setType(req.getOneKey());
            logTombUserRepair.setAreaId(areaId);
            logTombUserRepair.setProgress((int) (p * 1000));
            logTombUserRepair.setCost(String.valueOf(finalUseItemNum));
            AutoLogMgr.add(logTombUserRepair);

        });
    }

    @Override
    public void sendData(GamePlayer player) {

    }

    @Override
    public boolean isDebug() {
        return true;
    }

    @Override
    public String getRequestData() {
        return this.req.toString();
    }

}
